package lt20201221;

/**
 * 数组中占比超过一半的元素称之为主要元素。给定一个整数数组，找到它的主要元素。若没有，返回-1。
 * [1,2,5,9,5,9,5,5,5]
 * 5
 */
public class lt20201221 {
    public static int majorityElement(int[] nums) {
        int num = nums[0];
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (count >= 1) {
                if (nums[i] == num) {
                    count++;
                } else {
                    count--;
                }
            } else {
                count = 1;
                num = nums[i];
            }
        }
        count = 0;
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] == num) {
                count++;
            }
        }
        if (count > nums.length / 2) {
            return num;
        }
        return -1;
    }

    public static void main(String[] args) {
//        int[] nums = {2, 5, 5, 3, 3, 5, 6};
        int[] nums = {1, 2, 5, 9, 5, 9, 5, 5, 5};
        int i = majorityElement(nums);
        System.out.println(i);
    }
}
